package me.ilich.piet.interpreter;

import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import me.ilich.piet.interpreter.elements.Codel;
import me.ilich.piet.interpreter.elements.Program;

public class JPietInterpreter {
	
	private static final int sMaxIterationsCount = 10;
	
	private final Stack mStack = new StackImpl();
	
	public JPietInterpreter(){}
	
	public void setOutListener(Stack.OnOutListener listener){
		mStack.setOnOutListener(listener);
	}
	
	public void run(InputStream stream) throws InterpreterException {
		if(stream==null) throw new NullPointerException("stream");
		try {
			final BufferedImage image = ImageIO.read(stream);
			if(image==null) throw new InterpreterException("BufferedImage is null");
			Program prg = loadProgram(image);
			int iteration = 0;
			while(iteration<sMaxIterationsCount){
				iteration++;
			}
		} catch (IOException e) {
			throw new InterpreterException("IOException", e);
		}
	}

	private Program loadProgram(final BufferedImage image) {
		assert image!=null;
		int width = image.getWidth();
		int height = image.getHeight();
		Program prg = new Program(width, height);
		final WritableRaster raster = image.getRaster();
		for(int x=0; x<width; x++){
			for(int y=0; y<height; y++){
				int[] ar = null;
				int[] rgb = raster.getPixel(x, y, ar);
				Codel codel = Codel.fromRGB(rgb[0], rgb[1], rgb[2]);
				prg.setCodel(x, y, codel);
			}
		}
		assert prg!=null;
		return prg;
	}
	
	public static class InterpreterException extends Exception {
		
		private static final long serialVersionUID = -7279744272227315664L;

		public InterpreterException(String msg){
			super(msg);
		}
		
		public InterpreterException(String msg, Throwable throwable){
			super(msg, throwable);
		}
		
	}

}
